package handlers

import (
	"cron-go/configs/error_code"
	"cron-go/internal/pkg/crontab/dao"
	"cron-go/internal/pkg/crontab/models"

	"github.com/go-liam/util/conv"
	"github.com/go-liam/util/response"
	"github.com/go-playground/validator/v10"
)

type EditTask struct {
	Req   *EditTaskReq
	Model *models.TaskMysqlModel
	Data  interface{}
}

type EditTaskReq struct {
	ID           string      `json:"id" validate:"required" `
	Spec         string      `json:"spec" validate:"required" `
	Name         string      `json:"name" validate:"required" `
	Command      string      `json:"command"  `
	Config       interface{} `json:"config" validate:"required" `
	IsNotify     int8        `json:"isNotify" `
	NotifyConfig interface{} `json:"notifyConfig"  `
	WorkerType   int         `json:"workerType" `
	Label        interface{} `json:"label" `
}

func (s *EditTask) GetData() *response.APIResponse {
	if !s.CheckData() {
		return &response.APIResponse{Code: error_code.RequestParameter, Message: error_code.MsRequest, Data: response.DataItemNil}
	}
	s.ChangeModel()
	rs, _ := new(dao.TaskDao).Update(s.Model)
	data := make(map[string]interface{})
	data["item"] = ChangeTaskModelToResp(s.Model)
	data["rowsAffected"] = rs
	s.Data = data
	return &response.APIResponse{Code: error_code.Success, Message: error_code.MsSuccess, Data: s.Data}
}

func (s *EditTask) ChangeModel() {
	if s.Req == nil {
		return
	}
	s.Model = new(models.TaskMysqlModel)
	s.Model.Command = s.Req.Command
	s.Model.Name = s.Req.Name
	s.Model.Spec = s.Req.Spec
	s.Model.IsNotify = s.Req.IsNotify
	s.Model.WorkerType = s.Req.WorkerType
	s.Model.Label = conv.StructToJsonString(s.Req.Label)
	s.Model.NotifyConfig = conv.StructToJsonString(s.Req.NotifyConfig)
	s.Model.Config = conv.StructToJsonString(s.Req.Config)
	s.Model.ID = conv.StringToInt64(s.Req.ID, 0)
}

func (s *EditTask) CheckData() bool {
	validate := validator.New()
	err := validate.Struct(s.Req)
	return err == nil
}
